{% extends "base.html" %}

{% block title %}价格分布 - 惠农平台{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h3><i class="fas fa-chart-line me-2"></i>农产品不同时期价格分布</h3>
            </div>
            <div class="card-body">
                <!-- 筛选条件 -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <label for="categorySelect" class="form-label">选择类型</label>
                        <select class="form-select" id="categorySelect">
                            {% for category in categorized_products %}
                                <option value="{{ category }}">{{ category }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="productSelect" class="form-label">选择产品</label>
                        <select class="form-select" id="productSelect"></select>
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button type="button" class="btn btn-primary" id="refreshBtn">
                            <i class="fas fa-sync-alt me-1"></i>刷新图表
                        </button>
                    </div>
                </div>

                <!-- 图表容器 -->
                <div class="chart-container" style="min-height: 500px;">
                    <div id="priceDistributionChart" style="width: 100%; height: 500px;"></div>
                </div>

                <!-- 说明信息 -->
                <div class="mt-4">
                    <div class="alert alert-info">
                        <h5><i class="fas fa-info-circle me-2"></i>图表说明</h5>
                        <ul class="mb-0">
                            <li>本图表展示了选定农产品在不同时期的价格变化趋势。</li>
                            <li>可以通过选择不同的产品和时间粒度来查看不同的数据视图。</li>
                            <li>图表支持缩放、平移等交互操作。</li>
                            <li>鼠标悬停可查看详细的价格信息。</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
const categorizedProducts = {{ categorized_products | tojson | safe }};

function updateProductOptions() {
    const categorySelect = document.getElementById('categorySelect');
    const productSelect = document.getElementById('productSelect');
    const selectedCategory = categorySelect.value;
    const products = categorizedProducts[selectedCategory] || [];

    productSelect.innerHTML = '';
    if (products.length > 0) {
        products.forEach(product => {
            const option = document.createElement('option');
            option.value = product;
            option.textContent = product;
            productSelect.appendChild(option);
        });
    } else {
        const option = document.createElement('option');
        option.textContent = '该分类下无产品';
        productSelect.appendChild(option);
    }
}

async function updatePriceDistributionChart() {
    const productSelect = document.getElementById('productSelect');
    const chartContainer = document.getElementById('priceDistributionChart');

    if (!productSelect.value || productSelect.selectedOptions[0].textContent === '该分类下无产品') {
        chartContainer.innerHTML = '<div class="alert alert-warning">请先选择一个有效的产品。</div>';
        return;
    }

    const productName = encodeURIComponent(productSelect.value);
    chartContainer.innerHTML = `<div class="d-flex justify-content-center align-items-center" style="height: 100%;">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">加载中...</span>
                                    </div>
                                </div>`;

    try {
        const response = await fetch(`/api/price_distribution?product=${productName}`);
        const data = await response.json();

        if (data.error) {
            chartContainer.innerHTML = `<div class="alert alert-danger">${data.error}</div>`;
            return;
        }

        const categoryChart = JSON.parse(data.category_chart_json);
        if (categoryChart.data && categoryChart.data.length > 0) {
            // 核心修复：在绘制图表前，清空容器，移除加载动画
            chartContainer.innerHTML = '';
            Plotly.newPlot('priceDistributionChart', categoryChart.data, categoryChart.layout, { responsive: true });
        } else {
            chartContainer.innerHTML = '<div class="alert alert-info">暂无足够数据为该产品生成图表。</div>';
        }
    } catch (error) {
        console.error('Error fetching or rendering chart:', error);
        chartContainer.innerHTML = '<div class="alert alert-danger">加载图表时出错，请稍后重试。</div>';
    }
}
document.addEventListener('DOMContentLoaded', () => {
    const categorySelect = document.getElementById('categorySelect');
    const productSelect = document.getElementById('productSelect');
    const refreshBtn = document.getElementById('refreshBtn');

    categorySelect.addEventListener('change', () => {
        updateProductOptions();
        updatePriceDistributionChart();
    });

    refreshBtn.addEventListener('click', updatePriceDistributionChart);
    productSelect.addEventListener('change', updatePriceDistributionChart);

    // Initial load
    updateProductOptions();
    updatePriceDistributionChart();
});
</script>
{% endblock %} 